use std::{net::TcpListener, thread, sync::{mpsc::Sender}};

use snowflake::SnowflakeIdGenerator;

use crate::{server::{conf::ConfServer, func::{Function, UserFunction, ReqFunction}}, channel::http::prelude::NrReq };
use crate::channel::tcp::prelude::{ NrWriter, NrUReader };

/// 多线程启动http客户端监听
pub fn start(sx: &Sender<Box<dyn Function>>) {
    let server_conf = ConfServer::get_conf().unwrap();
    let http_listener = TcpListener::bind(("0.0.0.0", server_conf.port_http)).unwrap();
    println!("=====> http启动端口: {:?}", server_conf.port_http);
    for http_stream_result in http_listener.incoming() {
        let sx_clone = sx.clone();
        thread::spawn(move || {
            let http_stream = http_stream_result.unwrap();
            let mut generator = SnowflakeIdGenerator::new(1, 4);
            let uid = generator.generate();
            
            let writer = NrWriter::from(&http_stream);
            sx_clone.send(Box::new(UserFunction::new_update(uid, writer))).unwrap();

            let reader = &mut NrUReader::from(&http_stream).unwrap();
            loop {
                if !handle_connection(reader, &uid, &sx_clone) {
                    break;
                }
            }
        });
    }
}

fn handle_connection(reader: &mut NrUReader, uid: &i64, sx: &Sender<Box<dyn Function>>) -> bool {
    match NrReq::read_from_stream(reader) {
        Ok(request) => {
            let keep_alive = request.keep_alive();
            let mut generator = SnowflakeIdGenerator::new(1, 5);
            let pid = generator.generate();
            sx.send(Box::new(ReqFunction::new_update(pid, *uid, request))).unwrap();
            keep_alive
        },
        Err(_) => { sx.send(Box::new(UserFunction::new_remove(*uid))).unwrap(); false },
    }
}
